<?php
namespace Core\CoreComponents\TchatsManager;
use Core;

require_once(COMPONENTS_DIR . 'TchatsManager/ITchats.php');
require_once(CONTRACTS_DIR . 'tchatmessage.entity.php');

/**
* This interface provide all accessible methods on tchat module
*
* @method ServiceResponse addTchatMessage($message)
* @method ServiceResponse getTchatMessages()
* @method ServiceResponse deleteAllMessages()
*/
class Tchats implements ITchats
{
	/**
	 * Add a tchat message
	 *
	 * @param string $message The tchat message
	 * @param User $user The sender (user id)
	 * 
	 * @return ServiceResponse This response contains the added tchat message
	 */
	public function addTchatMessage($message, $user)
	{
		Core\CoreCommons\Logger::Info("addTchatMessage $message, $user");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$tchatMessage = Core\CoreContracts\TchatMessage::Create($message, $user);
			
			$result = $session->Save($tchatMessage);
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("TchatMessage $message added");
		}
		catch (Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	 * Get all tchat messages
	 *
	 * @todo DataStorage enhancement : Provide the full object using ID from complex properties
	 * 
	 * @return ServiceResponse This response contains all tchat messages
	 */
    public function getTchatMessages()
	{
		Core\CoreCommons\Logger::Info("Service - getTchatMessages");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
		
			$session->CreateCriteria('TchatMessage');
			$result = $session->ListResult();	
			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			
			Core\CoreCommons\Logger::Info("Service - getTchatMessages completed");
		}
		catch (\Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
	
	/**
	 * Delete all message from tchat
	 *
	 * @return ServiceResponse This response contains the deleted messages
	 */
	public function deleteAllMessages()
	{
		Core\CoreCommons\Logger::Info("deleteAllMessages");
		
		$response = null;
		
		try
		{	
			$session = Core\Datastorage\Session::Instance();
			$session->Open();
			
			$messages = $this->getTchatMessages()->response;
			
			$result = null;
			
			foreach($messages as $message)
			{
				$result = $session->Delete($message);
			}

			$response = new Core\CoreCommons\ServiceResponse($result);

			$session->Close();
			Core\CoreCommons\Logger::Info("All messages was deleted");
		}
		catch (Exception $ex) 
		{
			$response = Core\CoreCommons\ServiceResponse::CreateError($ex);
		}
		
		return $response;
	}
}

?> 